using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Delete : System.Web.UI.Page
{
    private const String CHECKED_ITEMS = "CheckedItems";
    protected void Page_Load(object sender, EventArgs e)
    {
        btnDeleteCheckedRuns.Attributes.Add("onclick", "return confirmDelete();");
        //If it is first time to page populate the drop downs
        if (!IsPostBack)
        {
            Session.Remove(CHECKED_ITEMS);
            PopulateTimeSpanDropDown();
            PopulateLoadTestDropdown(GetDropdownValue());
            Populate();

        }

        
    }

    private void PopulateTimeSpanDropDown()
    {
        if (IsPostBack) { return; }

        //TODO: create a datasource
        ddTimeSpan.Items.Clear();
        ddTimeSpan.Items.Add("All");
        ddTimeSpan.Items.Add("Today");
        ddTimeSpan.Items.Add("5");
        ddTimeSpan.Items.Add("10");
        ddTimeSpan.Items.Add("30");

        //default dropdwon to previous selection
        if (Session["pastDays"] != null)
        {
            int pastDays = (int)Session["pastDays"];
            if (pastDays > 0)
            {
                ddTimeSpan.Items.FindByValue(pastDays.ToString()).Selected = true;
            }
            else if (pastDays == 0)
            {
                ddTimeSpan.Items.FindByValue("Today").Selected = true;
            }
            else
            {
                ddTimeSpan.Items.FindByValue("All").Selected = true;
            }

        }


    }

    private void PopulateLoadTestDropdown(int DaysBefore)
    {
        //load test from the database
        DBHelper dbHelper = new DBHelper();
        ArrayList loadTests = dbHelper.GetLoadTests(DaysBefore);



        //bind results to the drop down
        this.ddLoadTests.DataSource = loadTests;
        this.ddLoadTests.DataBind();

        //set load test to the previous selected load test if it still exists
        if (Session["LoadTest"] != null)
        {
            string test = (string)Session["LoadTest"];

            try
            {
                ddLoadTests.Items.FindByValue(test).Selected = true;
            }
            catch
            {
                //ignore exception.  If test does not exist default to first item
            }
        }
        else
        {
            ddLoadTests.SelectedIndex = 0;
        }
    }


    public void Populate()
    {
        try
        {
            //configure the sql datasource with the correct input parameters
            if (Session["LoadTest"] != null)
            {
                string project = this.ddLoadTests.SelectedValue;
                int pastDays = GetDropdownValue();
                if (pastDays < 0) pastDays = int.MaxValue;

                this.SqlDataSource1.SelectParameters.Clear();
                this.SqlDataSource1.SelectParameters.Add("LoadTestName", project);

                Parameter p = new Parameter("PastDays", TypeCode.Int32, pastDays.ToString());
                this.SqlDataSource1.SelectParameters.Add(p);
            }

            //set the correct page
            if (Session["CurrentPageIndex"] != null)
            {
                this.gvDeleteRuns.PageIndex = (int)Session["CurrentPageIndex"];
            }
            this.gvDeleteRuns.DataBind();
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.ToString());
        }

    }


    private int GetDropdownValue()
    {
        if (ddTimeSpan.SelectedValue == "All")
            return -1;
        else if (ddTimeSpan.SelectedValue == "Today")
            return 0;
        else return int.Parse(ddTimeSpan.SelectedValue);
    }

    protected void btnHome_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx", false);
    }
    


    private void RememberOldValues()
    {
        List<int> deleteList = new List<int>();
        int index = -1;
        foreach (GridViewRow row in this.gvDeleteRuns.Rows)
        {
            index = (int)this.gvDeleteRuns.DataKeys[row.RowIndex].Value;
            bool result = ((CheckBox)row.FindControl("CheckBox1")).Checked;

            // Check in the Session
            if (Session[CHECKED_ITEMS] != null)
                deleteList = (List<int>)Session[CHECKED_ITEMS];
            if (result)
            {
                if (!deleteList.Contains(index))
                    deleteList.Add(index);
            }
            else
                deleteList.Remove(index);
        }
        if (deleteList != null && deleteList.Count > 0)
            Session[CHECKED_ITEMS] = deleteList;
    }

    private void RePopulateValues()
    {
        bool allChecked = true;
        List<int> deleteList = (List<int>)Session[CHECKED_ITEMS];
        if (deleteList != null && deleteList.Count > 0)
        {
            foreach (GridViewRow row in this.gvDeleteRuns.Rows)
            {
                int index = (int)this.gvDeleteRuns.DataKeys[row.RowIndex].Value;
                if (deleteList.Contains(index))
                {
                    CheckBox myCheckBox = (CheckBox)row.FindControl("CheckBox1");
                    myCheckBox.Checked = true;
                }
                else
                {
                    allChecked = false;
                }
            }
            if (allChecked)
            {
                CheckBox myCheckBox = (CheckBox)this.gvDeleteRuns.HeaderRow.FindControl("chkHeader");
                myCheckBox.Checked = true;
            }

        }

        
    }
    protected void gvDeleteRuns_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        //save the checked data
        RememberOldValues();

        //bind the grid view
        this.gvDeleteRuns.PageIndex = e.NewPageIndex;
        Populate();

        

    }
    protected void gvDeleteRuns_PreRender(object sender, EventArgs e)
    {
        //add back the check boxes
        RePopulateValues();
    }
    protected void btnDeleteCheckedRuns_Click(object sender, EventArgs e)
    {
        //save the checked data
        RememberOldValues();

        //delete the data
        List<int> deleteList = (List<int>)Session[CHECKED_ITEMS];
        if (deleteList == null)
        {

            return;
        }

        DBHelper helper = new DBHelper();
        helper.DeleteRuns(deleteList);

        //remove the checked item list
        Session.Remove(CHECKED_ITEMS);

        //repopulate the grid
        Populate();
    }

    protected void ddTimeSpan_SelectedIndexChanged(object sender, EventArgs e)
    {
        //clear the checked items
        Session.Remove(CHECKED_ITEMS);

        //set the number of days to search for results
        Session["pastDays"] = GetDropdownValue();

        //Update load test drop down to only have tests in the day range
        PopulateLoadTestDropdown(GetDropdownValue());

        //populate the grid view
        Populate();
    }
    protected void ddLoadTests_SelectedIndexChanged(object sender, EventArgs e)
    {
        //clear the checked items
        Session.Remove(CHECKED_ITEMS);

        //populate the grid view        
        Session["LoadTest"] = this.ddLoadTests.SelectedValue;
        Populate();
    }
    protected void chkSelectAll_Click(object sender, EventArgs e)
    {
        CheckBox headerCheckBox = (CheckBox)this.gvDeleteRuns.HeaderRow.FindControl("chkHeader");
                
        foreach (GridViewRow row in this.gvDeleteRuns.Rows)
        {            
            int index = (int)this.gvDeleteRuns.DataKeys[row.RowIndex].Value;
            if (!headerCheckBox.Checked)
            {
                RemoveIndex(index);
            }
            CheckBox myCheckBox = (CheckBox)row.FindControl("CheckBox1");
            myCheckBox.Checked = headerCheckBox.Checked;
            
        }
    }

    void RemoveIndex(int Index)
    {
        List<int> deleteList = (List<int>)Session[CHECKED_ITEMS];
        
        if (deleteList != null)
        {
            deleteList.Remove(Index);
        }
    }
}
